package transaction

import (
	"gorm.io/gorm"
	"log"
)

// 自定义 TxCommitter
type CustomTxCommitter struct {
	DB *gorm.DB
}

// 实现 TxCommitter 接口的 Commit 方法
func (c *CustomTxCommitter) Commit() error {
	// 执行自定义的提交事务逻辑
	return c.DB.Commit().Error
}

// 实现 TxCommitter 接口的 Rollback 方法
func (c *CustomTxCommitter) Rollback() error {
	// 执行自定义的回滚事务逻辑
	return c.DB.Rollback().Error
}

// 在事务中使用自定义的 TxCommitter
func main() {
	db, err := gorm.Open("mysql", "user:password@/dbname")
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()

	// 开启事务
	tx := db.Begin()

	// 使用自定义的 TxCommitter
	txCommitter := &CustomTxCommitter{DB: tx}

	// 在事务中执行操作
	// ...

	// 提交或回滚事务
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
	}
}

type Student struct {
	ID      int    `gorm:"primary_key"`
	Name    string `gorm:"not null"`
	Age     int    `gorm:"not null"`
	Grade   string `gorm:"not null"`
	Address string `gorm:"not null"`
}

func main1() {
	db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var student Student
	err = db.Where("id = ?", 1).First(&student).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			log.Print("No record found")
		} else {
			log.Print("Query failed", err)
		}
	} else {
		log.Printf("Found student: %+v", student)
	}
}
